
let {
	debug,
} = require('../config.js');

export class storagerBase {
	constructor(debug, sk = 'test',	needReset = false, keyValidator = () => true,	valueValidator = () => true) {
		this.debug = debug;
		this.sk = sk;
		this.needReset = needReset,
			this.keyValidator = keyValidator;
		this.valueValidator = valueValidator;
		if (this.needReset) {
			this.reset();
		}
	}
	reset() {
		const emptyDictJson = JSON.stringify({});
		wx.setStorageSync(this.sk, emptyDictJson);
	}
	checkKv(key, value) {
		if (!this.keyValidator(key)) {
			throw (
				`29-29 storageBase.js ${this.sk} method:syncSetKvDictByKey passed in arugmenst[1], syncSetKvDictByKey got invalid key: `,
				key);
		}
		if (!this.valueValidator(value)) {
			throw (
				`33-33 storageBase.js ${this.sk} method:syncSetKvDictByKey passed in arugmenst[1], syncSetKvDictByKey got invalid value: `,
				value);
		}
	}
	checkTobeKvDict(tobeCheckDict) {
		const that = this;
		Object.keys(tobeCheckDict).forEach(function(key) {
			const value = tobeCheckDict[key];
			that.checkKv(key, value)
		});
	}
	saveDict(newDict) {
		this.checkTobeKvDict(newDict);
		const newDictJson = JSON.stringify(newDict);
		wx.setStorageSync(this.sk, newDictJson);
	}
	syncGetKvDict() {
		let kvDict;
		try {
			const kvDictJson = wx.getStorageSync(this.sk);
			if (!kvDictJson) return {};
			kvDict = JSON.parse(kvDictJson);
			// console.log(`19-19 storageBase.js ${this.sk} method:syncGetKvDict kvDictJson: `, kvDictJson);
			return kvDict;
		} catch (err) {
			throw (err);
		}
	}
	syncGetValueByKey(key) {
		const kvDict = this.syncGetKvDict();
		return kvDict[key];
	}
	syncSetKvDictByKey(key, value, oldKvDict) {
		const that = this;
		let kvDict;
		if (!oldKvDict) {
			kvDict = syncGetUrlAndPicsrcKeyDict();
			console.log(`60-60 storageBase.js ${this.sk} method.syncSetdurlAndPicsrcDictByDurl read durlAndPicsrcDict from storage... durlAndPicsrcDict: ${JSON.stringify(kvDict)}`);
		}
		// console.log(`83-83  storageBase.js ${this.sk} method:syncSetKvDictByKey oldKvDict : JSON.stringify(oldKvDict)`);
		that.checkKv(key, value);
		kvDict = oldKvDict;
		kvDict[key] = value;
		// console.log(`85-85 storageBase.js ${this.sk} method:syncSetKvDictByKey new kvDict:`, JSON.stringify(kvDict));
		try {
			this.saveDict(kvDict);
		} catch (err) {
			throw (err);
		}
	}
	syncDropKvByKey(key) {
		if (!this.keyValidator(key)) {
			throw (`69-69 storageBase.js ${this.sk} method:syncDropKvByKey passed in arugmenst[1], got invalid key: ${key}`);
		}
		const kvDict = this.syncGetKvDict();
		if (key in kvDict) {
			delete kvDict[key];
			this.saveDict(kvDict);
			// console.log(`79-79 storageBase.js ${this.sk} invoke wx.syncDropKvByKey(key: "${key}") done.`);
		} else {
			console.log(`78-78 storageBase.js ${this.sk} method.syncDropKvByKey::  kvDict has no key equal key: ${key}`);
		}
	}
}